package com.fanrui.code.socket.netty.core;

import com.google.protobuf.MessageLite;

public abstract class MessageContext {
	private int requestNumber;
	private Session sender;
	private boolean responseIsSend;

	public MessageContext(int requestNumber, Session sender) {
		super();
		this.responseIsSend = false;
		this.requestNumber = requestNumber;
		this.sender = sender;
	}

	public Session getSender() {
		return sender;
	}

	/**
	 * 快捷方法。
	 * 
	 * @return
	 */
	public long getPlayerId() {
		return this.sender.getPlayerId();
	}

	/**
	 * 发送（客户端请求对应的）响应数据，注意对于一个Request，只能发送一次Response，再次发送会产生异常。
	 * 
	 * @param requestNumber
	 * @param response
	 */
	public void sendResponse(MessageLite response) {
		if (this.responseIsSend) {
			throw new IllegalStateException(
					String.format("Response已经发送一次，不能再次发送。%s %s", this.toString(), response.toString()));
		}
		this.sender.send(response);
		this.responseIsSend = true;
	}


	@Override
	public String toString() {
		return "RequestContext [requestNumber=" + requestNumber + ", sender=" + sender + ", responseIsSend="
				+ responseIsSend + "]";
	}
}
